import time
from flask_apscheduler import APScheduler
from apscheduler.triggers.interval import IntervalTrigger
from tasks.constants import PLATFORM_SCHEDULE
from tasks.utils import import_func

def init_scheduler(app):
    """初始化定时任务调度器"""
    scheduler = APScheduler()

    # 设置调度器配置
    app.config['SCHEDULER_API_ENABLED'] = True
    app.config['SCHEDULER_TIMEZONE'] = 'Asia/Shanghai' 

    # 初始化
    scheduler.init_app(app)

    def create_context_func(func_path):
        func = import_func(func_path)
        def wrapped_func():
            with app.app_context():
                return func(int(time.time()))
        return wrapped_func
    
    # 遍历平台配置，添加定时任务
    for config in PLATFORM_SCHEDULE.values():
        func = create_context_func(config["func_path"])
        interval = config["interval"]
        job_id = config["id"]
        job_name = config["name"]

        
        # 添加定时任务
        scheduler.add_job(
            func=func,
            trigger=IntervalTrigger(**interval),
            id=job_id,
            name=job_name,
        )

        print("添加定时任务:", job_name, "ID:", job_id, "间隔:", interval, "测试地址：", f"http://127.0.0.1:5000/run-task/{job_id}")

    
    scheduler.start()

    # 此处立即执行一次任务，不建议在DEBUG模式下使用，每次修改代码都会执行一次，导致产生大量数据库数据
    # 若数据库内没有数据，取消注释以下代码，执行一次任务，执行后再注释掉

    # for config in PLATFORM_SCHEDULE.values():
    #     job_id = config["id"]
    #     job_name = config["name"]
    #     job = scheduler.get_job(job_id)
    #     # 立即执行一次
    #     print(f"定时任务 {job_name} ({job_id}) 立即执行")
    #     job.func()
    
    print("定时任务调度器已启动")
    
    app.scheduler = scheduler

    @app.route('/run-task/<task_id>')
    def run_task(task_id):
        """手动运行指定任务

        Parameters:
            task_id: 任务 ID
        
        """
        job = scheduler.get_job(task_id)
        if job:
            job.func()
            return f"任务 {task_id} 已执行"
        return f"任务 {task_id} 不存在", 404